package com.chs.util;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.Map.Entry;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

/**
 * 
 * 发送邮箱工具类 泛型模板
 * 
 * @author mopeiwen
 * @version 2019年12月28日 下午3:59:43
 *
 */
public class EMailUtil {
	// 初始化配置文件
	private static Map<String, String> propertiesMap = new HashMap<String, String>();

	static {
		Properties prp = new Properties();
		InputStream inputStream = null;
		String path = "/mail.properties";
		try {
			inputStream = FileAccepterUtil.class.getResourceAsStream(path);
			BufferedReader bf = new BufferedReader(new InputStreamReader(inputStream));
			prp.load(bf);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		Set<Entry<Object, Object>> entrySet = prp.entrySet();
		Iterator<Entry<Object, Object>> iterator = entrySet.iterator();
		while (iterator.hasNext()) {
			Entry<Object, Object> entry = iterator.next();
			propertiesMap.put((String) entry.getKey(), (String) entry.getValue());
		}
	}

	/**
	 * 
	 * @param username
	 * @param random
	 * @param session
	 * @return
	 */
	public static String context(String username, String random) {
		String context = "<!DOCTYPE html>" + "<html>" + "<head>" + "<meta charset='utf-8' />"
				+ "<title>欢迎使用软工综合信息系统</title>" + "</head>" + "<body>" + "亲爱的用户，您好" + "<br/><br/>" + "您在 "
				+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ").format(new Date()) + "提交发送验证码的请求。" + "<br/><br/>"
				+ "以下是您的帐户及验证码信息：" + "<br/><br/>" + "帐    户：" + username + "<br/>" + "验证码：" + "<strong>" + random + "</strong>"
				+ "<br/><br/>" + "感谢您使用本系统。" + "<br/>" + "此为自动发送邮件，请勿直接回复！" + "</body>" + "</html>";
		return context;
	}
	
	/**
	 * 指定接收人并发送邮件
	 * 
	 * @param emails
	 *            接收人集合
	 * @param title
	 *            邮件标题
	 * @param msgContent
	 *            消息体
	 */
	public static void sendMail(List<String> emails, String title, String msgContent) {
		for (String string : emails) {
			try {
				sendMail(string, title, msgContent);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 指定接收人并发送邮件
	 * 
	 * @param email
	 *            接收人
	 * @param title
	 *            邮件标题
	 * @param msgContent
	 *            消息体
	 */
	public static void sendMail(String email, String title, String msgContent) {

		// 接收人邮箱
		String to = email;

		// 发件人电子邮箱
		String from = propertiesMap.get("from");

		// 发件人名称
		String name = propertiesMap.get("name");
		try {
			name = new String(name.getBytes(), "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		}

		// 指定发送邮件的主机为 smtp.qq.com
		String host = propertiesMap.get("host"); // QQ 邮件服务器

		// 获取系统属性
		Properties properties = System.getProperties();

		// 设置邮件服务器
		properties.setProperty(propertiesMap.get("system"), host);

		properties.put("mail.smtp.auth", "true");
		// 获取默认session对象
		Session session = Session.getDefaultInstance(properties, new Authenticator() {
			public PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(from, propertiesMap.get("password")); // 发件人邮件用户名、授权码
			}
		});

		try {
			// 创建默认的 MimeMessage 对象
			MimeMessage message = new MimeMessage(session);

			// Set From: 头部头字段
			message.setFrom(new InternetAddress(name + " <" + from + ">"));

			// Set To: 头部头字段
			message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

			// Set Subject: 头部头字段
			String encodedSubject = MimeUtility.encodeText(title, MimeUtility.mimeCharset("utf-8"), null);
			message.setSubject(encodedSubject);

			// 置入消息体
			message.setContent(msgContent, "text/html;charset=utf-8");// 设置邮件内容，为html格式

			// 发送消息
			Transport.send(message);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
